<%
if(true){
	out.println("活动已经结束");
	return;
}
%>
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="org.springframework.transaction.TransactionDefinition"%>
<%@page import="org.springframework.transaction.TransactionException"%>
<%@page import="org.springframework.transaction.support.DefaultTransactionDefinition"%>
<%@page import="org.springframework.transaction.PlatformTransactionManager"%>
<%@page import="org.springframework.transaction.TransactionStatus"%>
<%@page import="oracle.jdbc.driver.SQLUtil"%>
<%@page import="cn.jekun.component.core.service.gen.ErpOrdersService"%>
<%@page import="cn.jekun.component.core.service.gen.RsUserService"%>
<%@page import="cn.jekun.component.core.bean.gen.ErpOrders"%>
<%@page import="cn.jekun.component.core.bean.gen.RsUser"%>
<%@page import="cn.jekun.component.core.Constants"%>
<%@page import="cn.jekun.component.base.exceptions.BusinessException"%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import = "net.sf.json.JSONObject" %>
<%@ page import = "cn.jekun.component.base.utils.EncryptUtil"%>
<%@page import="cn.jekun.component.shop.service.OrderService"%>
<%@page import="cn.jekun.component.base.spring.SpringUtils"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- Basic Page Needs
================================================== -->
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no"/>  
<title>发放提货券</title>
<!-- Mobile Specific
================================================== -->
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1" />
<!-- CSS
================================================== -->
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/basic.js"></script>
<script type="text/javascript">
function doView(u){
	window.location="redEnvelopesList.jsp?userId=${param.userId}&mobile=${param.mobile}&phoneNum=${param.phoneNum}&url="+u;
}
function doSend(u){
	//判断是否选择
	var eles = document.getElementsByName("orderId");
	if(eles==null || eles.length ==0){
		alert("没有找到订单");
		return;
	}
	var flag = false;
	var orderId = null;
	for(var i=0;i<eles.length;i++){
		if(eles[i].checked){
			flag = true;
			orderId = eles[i].value;
			break;
		}
	}
	if(!flag){
		alert("请选择订单");
		return;
	}
	window.location='redEnvelopes.jsp?userId=${param.userId}&mobile=${param.mobile}&phoneNum=${param.phoneNum}&orderId='+orderId
			+'&url='+u;
}
</script>
</head>
<body>

<%
String startDate = "2015-01-01";//统计开始日期
String url = request.getParameter("url"); //扫描的路径
String userId = request.getParameter("userId"); //操作员的用户代码
String mobile = request.getParameter("mobile"); //操作员的mobile
String orderId = request.getParameter("orderId"); //订单号
String phoneNum = request.getParameter("phoneNum");//手機號碼
%>
	
	<%
	   if(url == null || "".equals(url)){//网页版本
	%>
	
	<%--头部 --%>
	<div class="header clearfix">
		<a href="phoneInput.jsp?userId=<%=userId==null?"":userId%>&mobile=<%=mobile==null?"":mobile%>"></a><span>操作员:<%=mobile==null?"":mobile%></span>
	</div>
	<%
	    }
	%>
	
   <!-- 查找抢提货券的代码 -->
   <%
     OrderService orderService = SpringUtils.getBean(OrderService.BEAN_NAME); //orderService实例对象
     ErpOrdersService erpOrdersService = SpringUtils.getBean(ErpOrdersService.BEAN_NAME); //ErpOrdersService
     RsUserService rsUserService = SpringUtils.getBean(RsUserService.BEAN_NAME);
     boolean orderFinishFlage = false;
    
     
     String createTime = "";
     List<Map> list = new ArrayList<Map>();
     int downSumCount = 0;
     int regSumCount = 0;
     Map sumCount = null;
     Map rsUser  = null;
     String scandUserId = "";
     String encodeUrl=null;
     
     //System.out.println("url = " + url + "&userId = " + userId);
     
     if(userId==null||userId.trim().length() == 0){
    	 out.print("<p style='color: red;'>非法访问</p>");
    	 return;
     }
     
     if(url != null && !("".equals(url))){//从app扫描二维码过来
     	int ind = url.indexOf("?u=");
     	if(ind == -1){//加密了？
     		encodeUrl = url;//密文
     		url = URLDecoder.decode(url,"UTF-8");//解密
     	}else{
     		encodeUrl = URLEncoder.encode(url, "UTF-8");//加密
     	}
     	ind = url.indexOf("?u=");
     	if(ind == -1){
     		 out.print("<p style='color: red;'>非法访问</p>");
        	 return;
     	}else{//传过来的的是url，加密了的
	     	scandUserId = url.substring(ind+3);
	     	scandUserId = EncryptUtil.decodeBase64(scandUserId);//扫二维码用戶代码(解密后)
     	}
     	
     	 String userSql = "select a.user_id,a.real_name,a.mobile from rs_user a where a.user_id = '"+scandUserId + "'";
	   	 rsUser = rsUserService.oneBySql(userSql);
	   	 if(rsUser == null){
	   		 out.print("<p style='color: red;'>用户不存在，请重新扫描</p>");
	   		 return;
	   	 }
     	
     }else if(phoneNum != null && !("".equals(phoneNum))){//从网页输入手机号码过来
    	 String userSql = "select a.user_id,a.real_name,a.mobile from rs_user a where a.mobile = '"+phoneNum + "'";
    	 rsUser = rsUserService.oneBySql(userSql);
    	 if(rsUser == null){
    		 out.print("<p style='color: red;'>手机号码不存在，请重新输入用户手机号码</p>");
    		 return;
    	 }
    	 scandUserId = rsUser.get("USER_ID").toString();
     }
     
   //判断网页版本是否已经登录
 	if((url==null || url.trim().length()==0) && !"1".equals( (String)session.getAttribute("_RED_ENVELOPERS_LOGIN_") ) ){
 		 out.print("<a style='color: red;' href='login.jsp?mobile='"+(mobile==null?"":mobile)+"'>超时或未登录，点这里请重新登录。</a>");
 		 return;
 	}
   
   String str="15353540144,18819158179,13533331795,15989008495,13432003679,18022455858,13719068226,13422154339,13420561913,13697452970,13711561365,13631464632,13668994569,15360699819,13710418780,13724051537,13794441039,18620229288,13710740338,13719330166,13711429386,18024666391,18102823031,13711626637,13480257898,18022355456,13435674881,13316014455,18822754485,13610289613,13533129989,15626002361,18218708654,13826089116,15914547672,13539837911,13650982575,13699714737,18520127916,18320086815,13533788241,18078848460,18718877395,18026216828,13570589251,18520786616,13535220504,13751766723,15975528056,13539969335,13824877955,13535226856,13416129716,15322835611,15710726393,13512770832,13539424983,13680075846,18022355468,13822189377,18027196409,13660880327,13760644261,18902497116,18986306615,13380041017,13427566540,13560476503,13922105910,15112003483,18819358439,18218676897,15814588734,13129389638,13728006733,13929540800,13570989257,18975717789,13560373809,15322364213,13060916089,13332845889,13726891358,18002245096,13668967473,13627950171,15013138187,15814849638,13249605137,13724770058,13434220279,15817095270,18922746090,18244941132,13416109102,13660407430,13719341965,13711519129,15815800844,15919655020,13316016871,18928742336,18202013143,13302210153,15622260695,13066364462,13026889975,15013282878,18898455315,13828421296";
   String m = (String)rsUser.get("MOBILE");
   if(str.indexOf(m)!=-1){//已经领取了
	   out.print("<span style='color:red'>该手机号码1月1日早上已经领取提货券，不能重复领取。</span>");
   	   return;
   }
   
   
     //发提货券
     if(orderId != null && !("".equals(orderId))){
    	 //判断用户否已经发放提货券
    	 //用户的提货券订单
     	String countSql = " select count(*) total from erp_orders a "
                  + " where exists (select 1 from erp_order_items c join erp_merchandise d on (c.merchandise_id = d.merchandise_id) " 
                  + " where c.order_id = a.order_id and d.merchandise_type_id='201412141000') "
                  //+ " and a.order_status_id='3' "
                  + " and a.out_order_id is not null"
                  + " and a.user_id = '" + scandUserId+"'"
                  + " and a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')"
                  ;
    	 int countResult = orderService.countBySql(countSql);
    	 if(countResult > 0 ){//已经发放
    		 out.println("<script>alert('对不起，每个人只能领一个提货券。');</script>");
    	 }else{
    	 
	    	 //判断订单是否有效
	    	 ErpOrders ord = erpOrdersService.one(orderId);
	    	 if(ord==null){
	    		 out.println("<script>alert('订单不存在，请重试');</script>");
	    	 }else{
		    	 if(!"1".equals(ord.getOrderStatusId())){//不是代发货 直发红包
		    		//out.println("<script>alert('订单状态不是待发货不允许发放提货券');</script>");
		    		//spring事务管理
			    		TransactionStatus transactionStatus = null;
			    		PlatformTransactionManager transactionManager = orderService.getTransactionManager();
			    		 try{
			    			   //开始事务	
			    			   if (transactionManager != null) {
			    					transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
			    				}
			    			 //发提货券
					    	 String updateSql="update erp_orders t set memo='B',evaluation_time=sysdate, out_order_id='"+userId+"' where t.order_id='"+orderId+"' "
					    			 +" and t.user_id='"+scandUserId+"' "//and t.order_status_id='1'
					    			 +" and not exists ("
					    			 +" select 1 from erp_orders a "
					    		     //+" where a.order_status_id='3' "
					    		     +" where a.out_order_id is not null "
					    		     +" and a.user_id='"+scandUserId+"'"
					    		     +" and a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')"
					    		     +" and exists(select 1 from erp_order_items c join erp_merchandise d on (c.merchandise_id = d.merchandise_id) "
					    			 +" where c.order_id = a.order_id and d.merchandise_type_id='201412141000' ) )";
					    	 Integer updateResult = (Integer)erpOrdersService.executeUpdate(updateSql);
					    	 if(updateResult==null || updateResult !=1){
					    		 throw new Exception("发放提货券错误(-1更新失败)");
					    	 }
				    	 	
				    	 	//最后再检查一次？？？
				    	 	countResult = orderService.countBySql(countSql);
					    	if(countResult > 1 ){//已经发放超过1次
					    		throw new Exception("发放提货券错误(-4重复发放)");
					    	}
				    	 	//提交事务
				    		if (transactionStatus != null) {
				    			transactionManager.commit(transactionStatus);
				    		}
			    		 }catch(Exception e){
			    			 out.println("<script>alert('"+e.getMessage()+"');</script>");
			    			 //回滚事务
			    			 if (transactionStatus != null) {
			    					try {
			    						transactionManager.rollback(transactionStatus);
			    					}
			    					catch (TransactionException tex) {
			    						throw tex;
			    					}
			    				}
			    		 }	
		    	 
		    	 
		    	 }else{//代发货:发货，完成订单
		    		//spring事务管理
		    		TransactionStatus transactionStatus = null;
		    		PlatformTransactionManager transactionManager = orderService.getTransactionManager();
		    		 try{
		    			   //开始事务	
		    			   if (transactionManager != null) {
		    					transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
		    				}
		    			 //发提货券
				    	 String updateSql="update erp_orders t set memo='A',evaluation_time=sysdate, out_order_id='"+userId+"' where t.order_id='"+orderId+"' "
				    			 +" and t.user_id='"+scandUserId+"' and t.order_status_id='1' "
				    			 +" and not exists ("
				    			 +" select 1 from erp_orders a "
				    		     //+" where a.order_status_id='3' "
				    		     +" where a.out_order_id is not null "
				    		     +" and a.user_id='"+scandUserId+"'"
				    		     +" and a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')"
				    		     +" and exists(select 1 from erp_order_items c join erp_merchandise d on (c.merchandise_id = d.merchandise_id) "
				    			 +" where c.order_id = a.order_id and d.merchandise_type_id='201412141000' ) )";
				    	 Integer updateResult = (Integer)erpOrdersService.executeUpdate(updateSql);
				    	 if(updateResult==null || updateResult !=1){
				    		 throw new Exception("发放提货券错误(-1更新失败)");
				    	 }
				    	 if(!orderService.shippingOrderBySystem(userId, orderId, "发提货券")){
				    		 throw new Exception("发放提货券错误(-2发货失败)");
				    	 }
			    	 	if(!orderService.finishOrderBySystem(userId, orderId, "发送提货券成功")){
			    	 		throw new Exception("发放提货券错误(-3完成失败)");
			    	 	}
			    	 	
			    	 	//最后再检查一次？？？
			    	 	countResult = orderService.countBySql(countSql);
				    	if(countResult > 1 ){//已经发放超过1次
				    		throw new Exception("发放提货券错误(-4重复发放)");
				    	}
			    	 	//提交事务
			    		if (transactionStatus != null) {
			    			transactionManager.commit(transactionStatus);
			    		}
		    		 }catch(Exception e){
		    			 out.println("<script>alert('"+e.getMessage()+"');</script>");
		    			 //回滚事务
		    			 if (transactionStatus != null) {
		    					try {
		    						transactionManager.rollback(transactionStatus);
		    					}
		    					catch (TransactionException tex) {
		    						throw tex;
		    					}
		    				}
		    		 }
		    		 
		    	 }
	    	 }
    	 }
     }
     //System.out.println("scandUserId = " + scandUserId);
     
     //用户的提货券订单
     String sql = " select a.order_id,a.create_time,b.shop_name,a.evaluation_time,a.out_order_id,a.order_status_id,st.order_status_name from erp_orders a "
                  + " join erp_shop b on (a.shop_id=b.shop_id) "
                  + " left join erp_order_status st on (a.order_status_id=st.order_status_id)"
                  + " where exists (select 1 from erp_order_items c join erp_merchandise d on (c.merchandise_id = d.merchandise_id) " 
                  + " where c.order_id = a.order_id and d.merchandise_type_id='201412141000')  "//and (a.order_status_id = '1' or a.order_status_id='3')
                  + " and a.user_id = '" + scandUserId +"'"
                  + " and a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')"
                  + " order by a.create_time desc";
     
     
     list = orderService.listBySql(sql);
     
     //统计发放发放提货券数量
     String sumSql = "select sum(case when a.out_order_id='"+userId+"' then 1 else 0 end) my_total,count(1)+169 total from erp_orders a "
    	 	         + " where exists ( select 1 from erp_order_items c join erp_merchandise d on (c.merchandise_id = d.merchandise_id) "
    			     + " where c.order_id = a.order_id and d.merchandise_type_id='201412141000' ) "
    			     + " and a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')"
    			     + " and a.out_order_id is not null";//即已经发放提货券
    			     //+ " and a.order_status_id='3'"; //--3是交易成功(即已经发放提货券)
     sumCount = orderService.oneBySql(sumSql);
     
 	// 统计注册数量
     String regSum = "select count(1) total from rs_user a where a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')";
     regSumCount = orderService.countBySql(regSum);
  	
     // 统计下载数量
     String downSum = "select count(1) total from ls_log a where a.log_type_id='14' and a.create_time >= to_date('"+startDate+"','yyyy-mm-dd')";
     downSumCount = orderService.countBySql(downSum);
     
     //判断是否已经发提货券
     for(int i = 0; i<list.size(); i++){
    	 Map orderStatues = list.get(i);
    	 if(orderStatues.get("OUT_ORDER_ID")!=null){//即已经发放提货券
    		 orderFinishFlage = true;  //订单完成交易的标志
    		 if(orderStatues.get("EVALUATION_TIME")!=null){
        		 createTime = orderStatues.get("EVALUATION_TIME").toString().substring(5,16); //完成時間
    		 }
        	 break;
    	 }
     }
     
   %>

	
	<div class="info cont">
	
		<%-- 用户信息 --%>
		<div class="top <%=orderFinishFlage?"red":"" %>">
			<p>
				<span>用户名：<%=rsUser.get("REAL_NAME")==null?rsUser.get("MOBILE"):rsUser.get("REAL_NAME") %></span>
			</p>
			<p>
				<span>手机号：<%=rsUser.get("MOBILE") %></span>
			</p>
	    <%
			 if(orderFinishFlage){
	     %>
			<p class="time">领取时间：<%=createTime%></p>
		<% 
		    }
		%>
		</div>
		
		<%-- 用户提货券订单信息 --%>
		<div class="main index" id="mainShow">
		    <table>
            <colgroup>
                <col/>
                <col/>
                <col/>
            </colgroup>
            <thead>
                <tr>
                    <th>订单尾号</th>
                    <th>下单时间</th>
                    <th>状态</th>
                </tr>
            </thead>
             <tbody>
		   <%
		   
		   for(int i=0;i<list.size();i++){
			   Map row = list.get(i);
		   %>
                <tr>
                    <td>
                        <table class="textLeft">
                            <tbody>
                                <tr>
                                <td>
                                    <% 
                                      if(!orderFinishFlage){
                                    %>
                                    <input type="radio" name="orderId" value = "<%=row.get("ORDER_ID")%>" />
                                    <%
                                      }
                                    %>
                                    &nbsp;
                                    </td>
                                    <td><%=row.get("ORDER_ID").toString().substring(10)%></td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                    <td>
                        <p><%=row.get("CREATE_TIME").toString().substring(5, 10)%></p>
                        <p><%=row.get("CREATE_TIME").toString().substring(11, 16)%></p>
                    </td>
                    <td>
                    <%
                     if(row.get("OUT_ORDER_ID")!=null){//已经发放提货券
                    %>
                    <span class="sendout">提货券</span>
                    <% } %>
                    <p><%=row.get("ORDER_STATUS_NAME") %></p></td>
                </tr>
		  <%	   
		   }
		   %>
		  </tbody>
        </table>
        
		</div>
		
		<%-- 统计信息 --%>
		<div class="bottom">
		    <p>
				<span>从<%=startDate%>开始</span>
			</p>
		    <p>
				<span>我已发提货券：<label style="color: red;font-weight: bold;"><%=sumCount.get("MY_TOTAL")==null?"0":sumCount.get("MY_TOTAL") %></label>个</span>
			</p>
			<p>
				<span>总共发提货券：<label style="color: red;font-weight: bold;"><%=sumCount.get("TOTAL")==null?"0":sumCount.get("TOTAL")%></label>个</span>
			</p>
			<p>
				<span>注册人数：<label style="color: red;font-weight: bold;"><%=regSumCount%></label>个</span>
			</p>
			<p>
				<span>下载量：<label style="color: red;font-weight: bold;"><%=downSumCount%></label>个</span>
			</p>
			
			

			<p>
				<span><br/><br/>
				2015-01-01总共发提货券：<label style="color: red;font-weight: bold;">430</label>个<br/>
				2015-01-02总共发提货券：<label style="color: red;font-weight: bold;">169</label>个
				</span>
			</p>
			
			
			<button type="button" class="check"
				onClick="doView('<%=encodeUrl==null?"":encodeUrl%>')">查看领提货券名单</button>
		</div>
	</div>
	         <%
			 if(list.size()>0 && !orderFinishFlage){
	          %>
	<div class="foot">
		<div class="cont">
		        <button type="button" class="send" onclick = "doSend('<%=encodeUrl==null?"":encodeUrl%>');">发放提货券</button>
		</div>
		<%} %>
	</div>
</body>
</html>